package com.xmut.mall.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xmut.mall.product.feign.CouponFeignService;
import com.xmut.mall.product.feign.MemberFeignService;
import com.xmut.mall.product.feign.WareFeignService;
import com.xmut.mall.product.searchparam.ManagerSkuComponentsSearchParam;
import com.xmut.mall.product.searchparam.SkuComponentsSearchParam;
import com.xmut.mall.product.searchparam.SkuPageSearchParam;
import com.xmut.mall.product.service.SkuDescService;
import com.xmut.mall.product.service.SkuImagesService;
import com.xmut.mall.product.service.SkuSaleAttrValueService;
import com.xmut.mall.product.utils.PageUtil;
import com.xmut.mall.product.utils.RespBean;
import com.xmut.mall.product.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.mall.product.utils.PageUtils;
import com.xmut.mall.product.utils.Query;

import com.xmut.mall.product.dao.SkuInfoDao;
import com.xmut.mall.product.entity.SkuInfoEntity;
import com.xmut.mall.product.service.SkuInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuDescService skuDescService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {

            queryWrapper.eq("catalog_id", catelogId).or();
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            queryWrapper.ge("price", min);
        }

        String max = (String) params.get("max");

        if (!StringUtils.isEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);

                if (bigDecimal.compareTo(new BigDecimal("0")) == 1) {
                    queryWrapper.le("price", max);
                }
            } catch (Exception e) {

            }

        }


        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 通过spuid查出所有的sku实体信息
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }

    /**
     * 获取sku的分页数据
     *
     * @param vo
     * @param searchParam
     * @return
     */
    @Override
    public RespBean getSkuByPage(PageVO vo, SkuPageSearchParam searchParam) {
        IPage<SkuPageVo> page = this.baseMapper.getSkuPage(PageUtil.initPage(vo), searchParam);

        return RespBean.success("获取成功", page);
    }

    /**
     * 编辑Sku
     *
     * @param vo
     * @return
     */
    @Override
    public RespBean editSku(EditSkuVo vo) {
        boolean update = this.update(new UpdateWrapper<SkuInfoEntity>().set("sku_name", vo.getSkuName())
                .set("sku_default_img", vo.getSkuImg()).set("price", vo.getPrice())
                .set("catalog_id", vo.getCateLogId())
                .set("brand_id", vo.getBrandId())
                .eq("sku_id", vo.getSkuId()));

        if (update) {
            return RespBean.success("操作成功");
        } else {
            return RespBean.error("操作失败");
        }

    }

    /**
     * 删除Sku
     *
     * @param skuId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean deleteSku(Long skuId) {
        boolean skuDescRemoveResult = skuDescService.removeById(skuId);
        boolean skuImagesRemoveResult = skuImagesService.removeById(skuId);
        boolean skuSaleAttrValueRemoveResult = skuSaleAttrValueService.removeById(skuId);
        boolean skuInfoRemoveResult = this.removeById(skuId);

        if (skuDescRemoveResult && skuImagesRemoveResult && skuSaleAttrValueRemoveResult && skuInfoRemoveResult) {
            return RespBean.success("删除成功");
        } else {
            try {
                throw new Exception("sku删除失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return RespBean.error("删除失败");
        }

    }

    /**
     * 根据参数获取Sku赠品
     *
     * @param params
     * @return
     */
    @Override
    public RespBean getSkuGiftByParams(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper();
        // 获取参数
        Long storeId = Long.parseLong(String.valueOf(params.get("storeId")));
//        String goodsName = String.valueOf(String.valueOf(params.get("goodsName")));
        // 根据商品Id匹配
        queryWrapper.eq("store_id", storeId);

        // 如果商品名称不为空就like匹配
//        if (!CharSequenceUtil.isNotBlank(goodsName)){
//            System.out.println("goodsName:"+goodsName);
//            queryWrapper.like("sku_name",goodsName);
//        }

        List<SkuInfoEntity> skuList = this.list(queryWrapper);

        return RespBean.success("获取成功", skuList);
    }

    /**
     * 获取sku选择组件的分页数据
     *
     * @param vo
     * @param param
     * @return
     */
    @Override
    public RespBean getSkuComponentsDataByPage(PageVO vo, SkuComponentsSearchParam param) {
        IPage<SkuInfoEntity> page = this.baseMapper.getSkuComponentsDataByPage(PageUtil.initPage(vo), param);

        return RespBean.success("获取成功", page);
    }

    /**
     * 根据参数获取商城官方管理端的sku礼物信息
     *
     * @param params
     * @return
     */
    @Override
    public RespBean getManagerSkuGiftByParams(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String goodsName = MapUtil.getStr(params, "goodsName");

        if (CharSequenceUtil.isNotEmpty(goodsName)) {
            queryWrapper.like("sku_name", goodsName);
        }

        List<SkuInfoEntity> list = this.list(queryWrapper);

        return RespBean.success("获取成功", list);


    }

    /**
     * 获取商城官方管理端的平台券所用的sku选择组件的分页数据
     *
     * @param vo
     * @param param
     * @return
     */
    @Override
    public RespBean getManagerSkuComponentsDataByPage(PageVO vo, ManagerSkuComponentsSearchParam param) {
        IPage<SkuInfoEntity> page = this.baseMapper.getManagerSkuComponentsDataByPage(PageUtil.initPage(vo), param);

        return RespBean.success("获取成功", page);
    }

    /**
     * 商品详情页点击立即购买 也就是BuyNow模式获取商品交易详情
     *
     * @param param
     * @return
     */
    @Override
    public RespBean getGoodPayDetailTypeBuyNow(Map<String, Object> param) {
        PayDetailVo vo = new PayDetailVo();
        Long userId = MapUtil.getLong(param, "userId");
        Long skuId = MapUtil.getLong(param, "skuId");
        Long spuId = MapUtil.getLong(param, "spuId");
        Long num = MapUtil.getLong(param, "num");
        List<Long> useChooseCouponIDS = MapUtil.get(param, "useCouponList", new cn.hutool.core.lang.TypeReference<List<Long>>() {
        });
        // 如果是null就转化为空集合
        if (CollUtil.isEmpty(useChooseCouponIDS)) {
            useChooseCouponIDS = new ArrayList<>();
        }
        vo.setUseCouponList(useChooseCouponIDS); // 保存之前选择优惠券
        SkuInfoEntity skuInfo = this.getById(skuId);


        // 组装carList 因为是直接从商品详情点进来没有购物车数据 所以直接组装
        CartVo cartVo = new CartVo();
        cartVo.setStoreId(skuInfo.getStoreId());
        cartVo.setStoreName(skuInfo.getStoreName());
        List<MemberCartVo> cartVoList = new ArrayList<>();
        MemberCartVo memberCartVo = new MemberCartVo();
        memberCartVo.setSkuId(skuId);
        memberCartVo.setSpuId(spuId);
        memberCartVo.setMemberId(userId);
        memberCartVo.setCatalogId(skuInfo.getCatalogId());
        memberCartVo.setSkuName(skuInfo.getSkuName());
        memberCartVo.setSkuImg(skuInfo.getSkuDefaultImg());
        memberCartVo.setSkuPrice(skuInfo.getPrice());
        memberCartVo.setProductCount(num);
        // 设置库存
        RespBean skuWareResp = wareFeignService.getSkuWareNumber(skuId);
        memberCartVo.setQuantity(Integer.parseInt(skuWareResp.getObj().toString()));
        // 计算小计
        memberCartVo.setSubTotal(new BigDecimal(num).multiply(skuInfo.getPrice()));
        cartVoList.add(memberCartVo);
        cartVo.setCatList(cartVoList);
        List<CartVo> cartVos = new ArrayList<>();
        cartVos.add(cartVo);
        vo.setCartList(cartVos);
        vo.setCheckedSkuList(cartVos);

        // 组装可以使用的优惠券
        param.put("cateId", skuInfo.getCatalogId());
        RespBean userAllCanUseCouponResp = memberFeignService.getUserAllCanUseCoupon(param);
        List<MemberCouponEntityVo> canUseCoupon = new ArrayList<>();
        if (userAllCanUseCouponResp.getCode() == 201) {
            canUseCoupon = JSON.parseObject(JSON.toJSONString(userAllCanUseCouponResp.getObj()), new TypeReference<List<MemberCouponEntityVo>>() {
            });
            // 防止空指针
            if (CollUtil.isEmpty(canUseCoupon)) {
                canUseCoupon = new ArrayList<>();
            }
        }
        vo.setCanUseCoupons(canUseCoupon);

        // 在可以使用的优惠券中过滤出用户选择使用的优惠券
        List<MemberCouponEntityVo> countCouponList = new ArrayList<>();
        // 如果选择的优惠券id不为空 以及 可用的优惠券不为空
        for (MemberCouponEntityVo memberCouponEntityVo : canUseCoupon) {
            for (Long useChooseCouponID : useChooseCouponIDS) {
                if (memberCouponEntityVo.getCouponId().equals(useChooseCouponID)) {
                    countCouponList.add(memberCouponEntityVo);
                }
            }
        }
        System.out.println("选中的优惠券" + countCouponList);


        // 计算priceDtail
        PriceDetailDTO priceDetailDTO = new PriceDetailDTO();
        BigDecimal originalPrice = skuInfo.getPrice().multiply(new BigDecimal(num));
        priceDetailDTO.setOriginalPrice(originalPrice); // 原始价格
        priceDetailDTO.setGoodsPrice(originalPrice);// 商品总金额（商品原价）
        BigDecimal freightPrice = BigDecimal.ZERO;
        priceDetailDTO.setFreightPrice(freightPrice); // 配送费 本功能还未做 先空着
        BigDecimal couponReducePrice = BigDecimal.ZERO;
        // 计算优惠券减掉的金额
        for (MemberCouponEntityVo memberCouponEntityVo : countCouponList) {
            // 如果优惠券是满减类型
            if (memberCouponEntityVo.getCouponType().equals("PRICE")) {
                // 判断是否满足使用金额
                if (originalPrice.compareTo(memberCouponEntityVo.getConsumeThreshold()) == 1) {
                    couponReducePrice = couponReducePrice.add(memberCouponEntityVo.getPrice());
                }
            }
            // 如果是满折类型
            if (memberCouponEntityVo.getCouponType().equals("DISCOUNT")) {
                // 将最早的总价拿来然后计算折数
                if (originalPrice.compareTo(memberCouponEntityVo.getConsumeThreshold()) == 1) {
                    BigDecimal discount = memberCouponEntityVo.getDiscount().multiply(new BigDecimal("0.1"));
                    BigDecimal disCountNum = originalPrice.subtract(originalPrice.multiply(discount));

                    couponReducePrice = couponReducePrice.add(disCountNum);
                }
            }
        }
        priceDetailDTO.setCouponPrice(couponReducePrice);// 优惠券减掉钱
        // 计算满减减掉的钱
        // feign调用查询现在可用的满减
        RespBean FullDiscountResp = couponFeignService.getProductDetailFullDiscount(skuId);
        List<FullDiscountEntityVo> fullDiscountList = JSON.parseObject(JSON.toJSONString(FullDiscountResp.getObj()), new TypeReference<List<FullDiscountEntityVo>>() {
        });
        // 防止空指针异常
        if (CollUtil.isEmpty(fullDiscountList)) {
            fullDiscountList = new ArrayList<>();
        }
        BigDecimal fullDiscountReducePrice = BigDecimal.ZERO;
        for (FullDiscountEntityVo fullDiscountEntityVo : fullDiscountList) {
            // 如果是减现金
            if (fullDiscountEntityVo.getFullMinusFlag()) {
                if (originalPrice.compareTo(fullDiscountEntityVo.getFullMoney()) == 1) {
                    fullDiscountReducePrice = fullDiscountReducePrice.add(fullDiscountEntityVo.getFullMinus());
                }
            } else {
                // 是满折
                if (originalPrice.compareTo(fullDiscountEntityVo.getFullMoney()) == 1) {
                    BigDecimal discount = fullDiscountEntityVo.getFullRate().multiply(new BigDecimal("0.1"));
                    BigDecimal disCountNum = originalPrice.subtract(originalPrice.multiply(discount));
                    fullDiscountReducePrice = fullDiscountReducePrice.add(disCountNum);
                }
            }
        }
        priceDetailDTO.setDiscountPrice(fullDiscountReducePrice); // 满减减掉的金额
        BigDecimal totalReduce = fullDiscountReducePrice.add(couponReducePrice); // 现在全部减掉的金额
        BigDecimal flowPrice = originalPrice.subtract(totalReduce).subtract(freightPrice); // 最终订单价格 总价-全部优惠(满减+优惠券)-运费
        priceDetailDTO.setFlowPrice(flowPrice);
        priceDetailDTO.setTotalNum(num);


        vo.setPriceDetailDTO(priceDetailDTO);

        return RespBean.success("获取成功", vo);
    }


}